package com.xjrsoft.module.organization.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.organization.dto.AddUserDto;
import com.xjrsoft.module.organization.dto.UpdateUserDto;
import com.xjrsoft.module.organization.dto.UserPageDto;
import com.xjrsoft.module.organization.dto.WeChatPageDto;
import com.xjrsoft.module.organization.entity.*;
import com.xjrsoft.module.organization.mapper.UserMapper;
import com.xjrsoft.module.organization.service.*;
import com.xjrsoft.module.organization.vo.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-03-02
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends MPJBaseServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    private final IUserDeptRelationService userDeptRelationService;

    private final IUserRoleRelationService userRoleRelationService;

    private final IUserPostRelationService userPostRelationService;

    private final IUserChargeDeptService userChargeDeptService;

    private final IDepartmentService departmentService;

    private final IPostService postService;

    private final IRoleService roleService;

    private final RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AddUserDto dto) {
        long count = count(Wrappers.<User>query().lambda().eq(User::getUserName, dto.getUserName()).or().eq(User::getCode, dto.getCode()));
        if (count > 0) {
            throw new MyException("用户名称或编码已存在");
        }
        User user = BeanUtil.toBean(dto, User.class);

        //密码加密加盐存储到数据库
        user.setPassword(SaSecureUtil.md5BySalt(dto.getPassword(), GlobalConstant.SECRET_KEY));

        save(user);
        dto.setId(String.valueOf(user.getId()));

        List<UserDeptRelation> userDeptRelationList = new ArrayList<>();
        if (StrUtil.isNotBlank(dto.getDepartmentIds())) {
            String allDeptIdStr = StrUtil.join(StringPool.COMMA, dto.getDepartmentIds());
            List<Long> departmentIds = Arrays.stream(allDeptIdStr.split(StringPool.COMMA)).map(Convert::toLong).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(departmentIds)) {
                for (Long deptId : departmentIds) {
                    //将用户所选部门保存到关联表中
                    UserDeptRelation userDeptRelation = new UserDeptRelation();
                    userDeptRelation.setUserId(user.getId());
                    userDeptRelation.setDeptId(deptId);
                    userDeptRelationList.add(userDeptRelation);
                }
            }
            userDeptRelationService.saveBatch(userDeptRelationList);
        }

        //将用户所选角色保存到关联表中
        List<UserRoleRelation> userRoleRelationList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dto.getRoleIds()) && dto.getRoleIds().size() > 0) {
            for (Long id : dto.getRoleIds()) {
                UserRoleRelation userRoleRelation = new UserRoleRelation();
                userRoleRelation.setRoleId(id);
                userRoleRelation.setUserId(user.getId());
                userRoleRelationList.add(userRoleRelation);
            }
            userRoleRelationService.saveBatch(userRoleRelationList);
        }

        //将用户所选岗位保存到关联表中
        List<UserPostRelation> userPostRelationList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dto.getPostIds()) && dto.getPostIds().size() > 0) {
            for (Long id : dto.getPostIds()) {
                UserPostRelation userPostRelation = new UserPostRelation();
                userPostRelation.setPostId(id);
                userPostRelation.setUserId(user.getId());
                userPostRelationList.add(userPostRelation);
            }
            userPostRelationService.saveBatch(userPostRelationList);
        }

        //将用户所负责的部门保存到关联表中
        List<UserChargeDept> userChargeDeptList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dto.getChargeDepartmentIds()) && dto.getChargeDepartmentIds().size() > 0) {
            for (Long id : dto.getChargeDepartmentIds()) {
                UserChargeDept userChargeDept = new UserChargeDept();
                userChargeDept.setDeptId(id);
                userChargeDept.setUserId(user.getId());
                userChargeDeptList.add(userChargeDept);
            }
            userChargeDeptService.saveBatch(userChargeDeptList);
        }

        //异步更新用户表、用户部门表、用户角色表、用户岗位表数据
        CompletableFuture.runAsync(() -> {
            List<User> list = list();
            redisUtil.set(GlobalConstant.USER_CACHE_KEY, list);

            List<UserDeptRelation> deptRelationList = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class));
            redisUtil.set(GlobalConstant.USER_DEPT_RELATION_CACHE_KEY, deptRelationList);

            List<UserRoleRelation> roleRelationList = userRoleRelationService.list(Wrappers.lambdaQuery(UserRoleRelation.class));
            redisUtil.set(GlobalConstant.USER_ROLE_RELATION_CACHE_KEY, roleRelationList);

            List<UserPostRelation> postRelationList = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class));
            redisUtil.set(GlobalConstant.USER_POST_RELATION_CACHE_KEY, postRelationList);

        });

        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(UpdateUserDto dto) {
        long count = count(Wrappers.<User>query().lambda()
                .eq(User::getCode, dto.getCode())
                .ne(User::getId, dto.getId()));

        if (count > 0) {
            throw new MyException("用户名称或编码已存在");
        }

        User user = BeanUtil.toBean(dto, User.class);

        updateById(user);

        //先删除再新增
        userDeptRelationService.remove(Wrappers.<UserDeptRelation>query().lambda().eq(UserDeptRelation::getUserId, user.getId()));
        userRoleRelationService.remove(Wrappers.<UserRoleRelation>query().lambda().eq(UserRoleRelation::getUserId, user.getId()));
        userPostRelationService.remove(Wrappers.<UserPostRelation>query().lambda().eq(UserPostRelation::getUserId, user.getId()));
        userChargeDeptService.remove(Wrappers.<UserChargeDept>query().lambda().eq(UserChargeDept::getUserId, user.getId()));

        List<UserDeptRelation> userDeptRelationList = new ArrayList<>();
        if (StrUtil.isNotBlank(dto.getDepartmentIds())) {
            String allDeptIdStr = StrUtil.join(StringPool.COMMA, dto.getDepartmentIds());
            List<Long> departmentIds = Arrays.stream(allDeptIdStr.split(StringPool.COMMA)).map(Convert::toLong).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(departmentIds)) {
                for (Long deptId : departmentIds) {
                    //将用户所选部门保存到关联表中
                    UserDeptRelation userDeptRelation = new UserDeptRelation();
                    userDeptRelation.setUserId(user.getId());
                    userDeptRelation.setDeptId(deptId);
                    userDeptRelationList.add(userDeptRelation);
                }
            }
            userDeptRelationService.saveBatch(userDeptRelationList);
        }

        //将用户所选角色保存到关联表中
        List<UserRoleRelation> userRoleRelationList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dto.getRoleIds()) && dto.getRoleIds().size() > 0) {
            for (Long id : dto.getRoleIds()) {
                UserRoleRelation userRoleRelation = new UserRoleRelation();
                userRoleRelation.setRoleId(id);
                userRoleRelation.setUserId(user.getId());
                userRoleRelationList.add(userRoleRelation);
            }
            userRoleRelationService.saveBatch(userRoleRelationList);
        }

        //将用户所选岗位保存到关联表中
        List<UserPostRelation> userPostRelationList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dto.getPostIds()) && dto.getPostIds().size() > 0) {
            for (Long id : dto.getPostIds()) {
                UserPostRelation userPostRelation = new UserPostRelation();
                userPostRelation.setPostId(id);
                userPostRelation.setUserId(user.getId());
                userPostRelationList.add(userPostRelation);
            }
            userPostRelationService.saveBatch(userPostRelationList);
        }

        //将用户所负责的部门保存到关联表中
        List<UserChargeDept> userChargeDeptList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dto.getChargeDepartmentIds()) && dto.getChargeDepartmentIds().size() > 0) {
            for (Long id : dto.getChargeDepartmentIds()) {
                UserChargeDept userChargeDept = new UserChargeDept();
                userChargeDept.setDeptId(id);
                userChargeDept.setUserId(user.getId());
                userChargeDeptList.add(userChargeDept);
            }
            userChargeDeptService.saveBatch(userChargeDeptList);
        }

        //异步更新用户表、用户部门表、用户角色表、用户岗位表数据
        CompletableFuture.runAsync(() -> {
            List<User> list = list();
            redisUtil.set(GlobalConstant.USER_CACHE_KEY, list);

            List<UserDeptRelation> deptRelationList = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class));
            redisUtil.set(GlobalConstant.USER_DEPT_RELATION_CACHE_KEY, deptRelationList);

            List<UserRoleRelation> roleRelationList = userRoleRelationService.list(Wrappers.lambdaQuery(UserRoleRelation.class));
            redisUtil.set(GlobalConstant.USER_ROLE_RELATION_CACHE_KEY, roleRelationList);

            List<UserPostRelation> postRelationList = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class));
            redisUtil.set(GlobalConstant.USER_POST_RELATION_CACHE_KEY, postRelationList);
        });
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        //删除时需要同时删除用户部门关联表和用户角色关联表和用户岗位关系表和用户负责部门关联表的数据。
        this.removeBatchByIds(ids);
        //根据用户ids去缓存中查询到对应的三个表的数据
        List<UserDeptRelation> userDeptRelationList = redisUtil.get(GlobalConstant.USER_DEPT_RELATION_CACHE_KEY, new TypeReference<List<UserDeptRelation>>() {
        });
        List<UserPostRelation> userPostRelationList = redisUtil.get(GlobalConstant.USER_POST_RELATION_CACHE_KEY, new TypeReference<List<UserPostRelation>>() {
        });
        List<UserRoleRelation> userRoleRelationList = redisUtil.get(GlobalConstant.USER_ROLE_RELATION_CACHE_KEY, new TypeReference<List<UserRoleRelation>>() {
        });
        List<UserChargeDept> userChargeDeptList = userChargeDeptService.list();
        //拿用户ids进行过滤，如果存在，就删除
        List<Long> deptRelationIds = userDeptRelationList.stream().filter(u -> ids.contains(u.getUserId())).map(UserDeptRelation::getId).collect(Collectors.toList());
        List<Long> postRelationIds = userPostRelationList.stream().filter(u -> ids.contains(u.getUserId())).map(UserPostRelation::getId).collect(Collectors.toList());
        List<Long> roleRelationIds = userRoleRelationList.stream().filter(u -> ids.contains(u.getUserId())).map(UserRoleRelation::getId).collect(Collectors.toList());
        List<Long> userChargeIds = userChargeDeptList.stream().filter(u -> ids.contains(u.getUserId())).map(UserChargeDept::getId).collect(Collectors.toList());
        //调用四个表的删除
        if (CollectionUtil.isNotEmpty(deptRelationIds)) {
            userDeptRelationService.removeBatchByIds(deptRelationIds);
        }
        if (CollectionUtil.isNotEmpty(postRelationIds)) {
            userPostRelationService.removeBatchByIds(postRelationIds);
        }
        if (CollectionUtil.isNotEmpty(roleRelationIds)) {
            userRoleRelationService.removeBatchByIds(roleRelationIds);
        }
        if (CollectionUtil.isNotEmpty(userChargeIds)) {
            userChargeDeptService.removeBatchByIds(userChargeIds);
        }
        //更新缓存
        CompletableFuture.runAsync(() -> {
            List<User> list = this.list();
            redisUtil.set(GlobalConstant.USER_CACHE_KEY, list);

            List<UserDeptRelation> deptRelationList = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class));
            redisUtil.set(GlobalConstant.USER_DEPT_RELATION_CACHE_KEY, deptRelationList);

            List<UserPostRelation> postRelationList = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class));
            redisUtil.set(GlobalConstant.USER_POST_RELATION_CACHE_KEY, postRelationList);

            List<UserRoleRelation> roleRelationList = userRoleRelationService.list(Wrappers.lambdaQuery(UserRoleRelation.class));
            redisUtil.set(GlobalConstant.USER_ROLE_RELATION_CACHE_KEY, roleRelationList);
        });
        return Boolean.TRUE;
    }

    @Override
    public List<UserInfoVo> getUsersInfo(List<Long> ids) {

        if (CollectionUtils.isEmpty(ids) || ObjectUtil.isNull(ids.get(0))) {
            return new ArrayList<>();
        }

        List<User> list = userMapper.selectList(Wrappers.lambdaQuery(User.class)
                .in(User::getId, ids)
                .select(User.class, x -> VoToColumnUtil.fieldsToColumns(UserInfoVo.class).contains(x.getProperty())));

        return BeanUtil.copyToList(list, UserInfoVo.class);
    }

    @Override
    public PageOutput<WeChatPageVO> getPage(WeChatPageDto dto) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(dto.getKeyword()), User::getName, dto.getKeyword())
                .select(User.class, x -> VoToColumnUtil.fieldsToColumns(WeChatPageVO.class).contains(x.getProperty()));
        IPage<User> page = userMapper.selectPage(ConventPage.getPage(dto), queryWrapper);
        List<User> records = page.getRecords();
        for (User record : records) {
            record.setRemark("员工更新成功");
            record.setSortCode(1);
        }
        return ConventPage.getPageOutput(page, WeChatPageVO.class);

    }

    public PageOutput<UserPageVo> page(UserPageDto dto) {
        List<Long> deptIds = new ArrayList<>();
        if (ObjectUtil.isNotNull(dto.getDepartmentId())) {
            List<Department> list = redisUtil.get(GlobalConstant.DEP_CACHE_KEY, new TypeReference<List<Department>>() {
            });
            //当前部门的层级
            String hierarchy = list.stream().filter(x -> x.getId().equals(dto.getDepartmentId())).findFirst().orElse(new Department()).getHierarchy();
            if (StrUtil.isNotBlank(hierarchy)) {
                //层级里面包含当前部门层级的就是它的子集，如1-1，下面包含了1-1、1-1-2这种
                deptIds = list.stream().filter(x -> StrUtil.isNotBlank(x.getHierarchy()) && x.getHierarchy().contains(hierarchy)).map(Department::getId).collect(Collectors.toList());
            } else {
                //如果不存在层级就查询自己的数据
                deptIds.add(dto.getDepartmentId());
            }
        }

        //因为多表关联 会有多个表都使用了id字段，  所以必须专门指定主表的Id
        if (ObjectUtil.isNotNull(dto.getDepartmentId())) {//不为空联合查询
            IPage<UserPageVo> page = this.selectJoinListPage(ConventPage.getPage(dto), UserPageVo.class,
                    MPJWrappers.<User>lambdaJoin()
                            .distinct()
                            .and(StrUtil.isNotBlank(dto.getKeyword()),
                                    x -> x.like(User::getCode, dto.getKeyword()).or().like(User::getName, dto.getKeyword()))
                            .like(StrUtil.isNotBlank(dto.getUserName()), User::getUserName, dto.getUserName())
                            .like(StrUtil.isNotBlank(dto.getCode()), User::getCode, dto.getCode())
                            .like(StrUtil.isNotBlank(dto.getName()), User::getName, dto.getName())
                            .like(StrUtil.isNotBlank(dto.getMobile()), User::getMobile, dto.getMobile())
                            .in(ObjectUtil.isNotNull(dto.getDepartmentId()), UserDeptRelation::getDeptId, deptIds)
                            .orderByDesc(User::getCreateDate)
                            .select(User::getId)
                            .select(User.class, x -> VoToColumnUtil.fieldsToColumns(UserPageVo.class).contains(x.getProperty()))
                            .leftJoin(UserDeptRelation.class, UserDeptRelation::getUserId, User::getId));
            return ConventPage.getPageOutput(page);
        } else {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StrUtil.isNotBlank(dto.getKeyword()), User::getName, dto.getKeyword())
                    .or(StrUtil.isNotBlank(dto.getKeyword()), x -> x.like(StrUtil.isNotBlank(dto.getKeyword()), User::getCode, dto.getKeyword()))
                    .like(StrUtil.isNotBlank(dto.getUserName()), User::getUserName, dto.getUserName())
                    .like(StrUtil.isNotBlank(dto.getCode()), User::getCode, dto.getCode())
                    .like(StrUtil.isNotBlank(dto.getName()), User::getName, dto.getName())
                    .like(StrUtil.isNotBlank(dto.getMobile()), User::getMobile, dto.getMobile())
                    .orderByDesc(User::getCreateDate)
                    .select(User.class, x -> VoToColumnUtil.fieldsToColumns(UserPageVo.class).contains(x.getProperty()));

            IPage<User> page = this.page(ConventPage.getPage(dto), queryWrapper);
            return ConventPage.getPageOutput(page, UserPageVo.class);
        }
    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public UserVo getInfo(Long id) {
        User user = this.getById(id);
        if (user == null) {
            throw new RuntimeException("找不到此用户！");
        }
        UserInfoVo currentInfo = this.getCurrentInfo(user);
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        List<Long> deptIds = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class)
                        .eq(UserDeptRelation::getUserId, user.getId()))
                .stream().map(UserDeptRelation::getDeptId).collect(Collectors.toList());
        String allDeptIdStr = StrUtil.join(StringPool.COMMA, deptIds);
        userVo.setDepartmentIds(allDeptIdStr);
        userVo.setRoles(currentInfo.getRoles());
        userVo.setPosts(currentInfo.getPosts());
        userVo.setChargeDepartments(currentInfo.getChargeDepartments());
        return userVo;
    }

    @Override
    public UserInfoVo getCurrentInfo(User user) {

        List<Long> roleIds = userRoleRelationService.list(Wrappers.lambdaQuery(UserRoleRelation.class)
                        .eq(UserRoleRelation::getUserId, user.getId()))
                .stream().map(UserRoleRelation::getRoleId).collect(Collectors.toList());

        List<Long> deptIds = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class)
                        .eq(UserDeptRelation::getUserId, user.getId()))
                .stream().map(UserDeptRelation::getDeptId).collect(Collectors.toList());

        List<Long> postIds = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class)
                        .eq(UserPostRelation::getUserId, user.getId()))
                .stream().map(UserPostRelation::getPostId).collect(Collectors.toList());

        List<Long> chargeDeptIds = userChargeDeptService.list(Wrappers.lambdaQuery(UserChargeDept.class)
                        .eq(UserChargeDept::getUserId, user.getId()))
                .stream().map(UserChargeDept::getDeptId).collect(Collectors.toList());

        UserInfoVo vo = BeanUtil.toBean(user, UserInfoVo.class);
        if (roleIds.size() > 0) {

            List<Role> list = roleService.list(Wrappers.lambdaQuery(Role.class).in(Role::getId, roleIds));
            List<UserRoleVo> userRoleVoList = BeanUtil.copyToList(list, UserRoleVo.class);
            vo.setRoles(userRoleVoList);

        }

        if (deptIds.size() > 0) {
            List<Department> list = departmentService.list(Wrappers.lambdaQuery(Department.class).in(Department::getId, deptIds));
            List<UserDeptVo> userDeptVoList = BeanUtil.copyToList(list, UserDeptVo.class);
            vo.setDepartments(userDeptVoList);

        }

        if (postIds.size() > 0) {
            List<Post> list = postService.list(Wrappers.lambdaQuery(Post.class).in(Post::getId, postIds));
            List<UserPostVo> userPostVoList = BeanUtil.copyToList(list, UserPostVo.class);
            vo.setPosts(userPostVoList);

        }

        if (chargeDeptIds.size() > 0) {
            List<Department> list = departmentService.list(Wrappers.lambdaQuery(Department.class).in(Department::getId, chargeDeptIds));
            List<UserDeptVo> userDeptVoList = BeanUtil.copyToList(list, UserDeptVo.class);
            vo.setChargeDepartments(userDeptVoList);
        }
        return vo;
    }

    @Override
    public Boolean importData(MultipartFile file) throws IOException {
        List<UserExportVo> userExportVos = EasyExcel.read(file.getInputStream()).head(UserExportVo.class).sheet().doReadSync();
        List<User> users = BeanUtil.copyToList(userExportVos, User.class);
        //获取所有的字典项
        List<User> list = list();
        for (User user : users) {
            List<User> count = list.stream().filter(x -> x.getCode().equals(user.getCode())
                    || x.getName().equals(user.getName())).collect(Collectors.toList());
            if (count.size() > 0) {
                throw new MyException("导入的项目名或者编码已经存在！项目名称为：" + user.getName());
            }
        }
        //批量保存用户信息
        boolean isSuccess = saveBatch(users);
        //因为不想在循环里面写插入语句，所以需重新获取所有的用户项，主要获取创建人为登录人，并且创建时间为前后五分钟内的数据
        LocalDateTime nowTime = LocalDateTime.now();
        List<User> saveUserData = list(Wrappers.<User>lambdaQuery().eq(User::getCreateUserId, StpUtil.getLoginIdAsLong())
                .between(User::getCreateDate, nowTime.minusMinutes(5), nowTime.plusMinutes(5)));
        List<UserDeptRelation> userDeptRelationList = new ArrayList<>();
        for (UserExportVo userExportVo : userExportVos) {//保存用户部门数据
            //找到之前保存的用户信息的数据，需要使用到userId
            Optional<User> first = saveUserData.stream().filter(x -> x.getName().equals(userExportVo.getName()) && x.getCode().equals(userExportVo.getCode())).findFirst();
            if (first.isPresent()) {
                Long userId = first.get().getId();
                if (StrUtil.isNotBlank(userExportVo.getDepartmentIds())) {
                    //分割deptId
                    List<Long> deptIds = Arrays.stream(userExportVo.getDepartmentIds().split(StringPool.COMMA)).map(Convert::toLong).collect(Collectors.toList());
                    for (Long deptId : deptIds) {
                        UserDeptRelation userDeptRelation = new UserDeptRelation();
                        userDeptRelation.setDeptId(deptId);
                        userDeptRelation.setUserId(userId);
                        userDeptRelationList.add(userDeptRelation);
                    }
                }
            }
        }
        //批量保存用户部门数据
        userDeptRelationService.saveBatch(userDeptRelationList);
        return isSuccess;
    }
}
